package xyz.hubery.listener;


import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.hubery.model.Constants;
import xyz.hubery.pojo.CartGoods;
import xyz.hubery.service.CartService;

@Slf4j
@Service
@RocketMQMessageListener(
        topic = Constants.UPDATE_CART_TOPIC,
        consumerGroup = "update_cart_group",
        consumeMode = ConsumeMode.ORDERLY // 顺序消费
)
public class RefreshCartGoodsListener implements RocketMQListener<CartGoods>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private CartService cartService;


    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        // 设置为顺序消费
        defaultMQPushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
    }


    @Override
    public void onMessage(CartGoods cartGoods) {

        if(Constants.SYNC_GOODS_TAG.equals(cartGoods.getTag())) {
            log.info("更新购物车缓存中的商品数据：{}",cartGoods);
            cartService.refreshCartGoods(cartGoods);
        }else if(Constants.DEL_GOODS_TAG.equals(cartGoods.getTag())){
            log.info("删除购物车缓存中的商品数据：{}",cartGoods.getGoodId());
            cartService.deleteCartGoods(cartGoods.getGoodId());
        }

    }

}
